package com.aplana.ccsd.renderer;

import info.magnolia.beanmerger.BeanMergerUtil;
import info.magnolia.module.templatingkit.sites.Site;
import info.magnolia.module.templatingkit.templates.DefaultSTKTemplateConfiguration;
import info.magnolia.module.templatingkit.templates.pages.STKPage;
import info.magnolia.module.templatingkit.util.STKUtil;
import info.magnolia.rendering.context.RenderingContext;
import info.magnolia.rendering.engine.RenderException;
import info.magnolia.rendering.renderer.FreemarkerRenderer;
import info.magnolia.rendering.template.RenderableDefinition;

import java.util.Map;

import javax.jcr.Node;

import org.apache.jackrabbit.commons.JcrUtils;

public class MyRenderer extends FreemarkerRenderer {

    @Override
    public void render(final RenderingContext renderingCtx, Map<String, Object> contextObjects) throws RenderException {
        Node content = renderingCtx.getCurrentContent();
        
        Node mainContent = renderingCtx.getMainContent();
        
        //for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
            //.out.println(ste);
        //}

        //System.out.println("Content: " + content);
        
        //System.out.println("MainContent: " + mainContent);
        
        // FIXME for the time being we only render pages and areas but not components
        try {
            final Site site = getSite(content);
            RenderableDefinition renderableDefinition = renderingCtx.getRenderableDefinition();
            // merge in case of a page
            if (renderableDefinition instanceof STKPage) {
                renderableDefinition = (RenderableDefinition) BeanMergerUtil.merge(renderableDefinition, site.getTemplates().getPrototype(), DefaultSTKTemplateConfiguration.getInstance());
                String dialog = ((STKPage) renderableDefinition).getDialog();
                //System.out.println("Dialog: " + dialog);
            }
            // FIXME we should not push() if the definition is not merged
            renderingCtx.push(content, renderableDefinition);
            try{
                super.render(renderingCtx, contextObjects);
            } finally {
                renderingCtx.pop();
            }
        } catch (Exception e) {
            throw new RenderException(e);
        }
    }

    protected Site getSite(Node node) {
        final Site site = STKUtil.getSite();
        if(site == null){
            throw new IllegalStateException("No site configuration found for [" + JcrUtils.toString(node) + "]");
        }
        return site;
    }




}
